package com.yuqing.sentimentapp.login.acitivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.linkface.baselibrary.http.BaseBean;
import com.linkface.baselibrary.utils.AppManager;
import com.linkface.baselibrary.utils.LogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.wework.api.IWWAPI;
import com.tencent.wework.api.IWWAPIEventHandler;
import com.tencent.wework.api.WWAPIFactory;
import com.tencent.wework.api.model.BaseMessage;
import com.tencent.wework.api.model.WWAuthMessage;
import com.yuqing.sentimentapp.BuildConfig;
import com.yuqing.sentimentapp.Constants;
import com.yuqing.sentimentapp.MainActivity;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.yuqing.sentimentapp.home.acitivity.NewsDetailActivity;
import com.yuqing.sentimentapp.interfaces.ScheduleListener;
import com.yuqing.sentimentapp.jpush.TagAliasOperatorHelper;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.utils.AppUtil;
import com.yuqing.sentimentapp.utils.InstallUtil;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.utils.UpdateAppManager;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ShenHe on 2019/3/9.
 */

public class LoginActivity extends BaseActivity {
    private static final String URL_PRIVACY_VOLICY = BuildConfig.Base_URL + "/public/html/privacy.html";
    private static final String URL_USER_PROTOCOL = BuildConfig.Base_URL + "/public/html/user-agreement.html";

    private IWWAPI iwwapi;

    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.iv_clear)
    ImageView mIvClear;
    @BindView(R.id.iv_wechat_login)
    ImageView mIvWechatLogin;
    @BindView(R.id.btn_next_step)
    Button mBtnNextStep;
    @BindView(R.id.tv_user_protocol)
    TextView mTvUserProtocol;
    @BindView(R.id.tv_privacy_policy)
    TextView mPrivacyPolicy;
    private String taskFilePath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 避免从桌面启动程序后，会重新实例化入口类的activity
        Intent intent = getIntent();
        if (!isTaskRoot()
                && intent != null
                && intent.hasCategory(Intent.CATEGORY_LAUNCHER)
                && intent.getAction() != null
                && intent.getAction().equals(Intent.ACTION_MAIN)) {
            finish();
            return;
        }
        if (SharePrefrenceHelper.checkLoginStatus()) {
            turnToMain();
        } else {
            if (!JPushInterface.isPushStopped(getApplicationContext())) {
                JPushInterface.stopPush(getApplicationContext());
            }
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initPresenter() {
        //初始化微信注册
        initEnterpriseWX();
        //请求权限
        requestPermission();

        checkUpdate();
    }

    private void turnToMain() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void initView() {
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
                    mIvClear.setVisibility(View.GONE);
                    mBtnNextStep.setEnabled(false);
                } else {
                    mIvClear.setVisibility(View.VISIBLE);
                    mBtnNextStep.setEnabled(true);
                }
            }
        });
    }

    private void checkUpdate() {//检查更新
        UpdateAppManager.getUpdateAppManager().init();
        UpdateAppManager.getUpdateAppManager().onlineCheckAppUpdate(new ScheduleListener() {
            @Override
            public void progress(int progress) {

            }

            @Override
            public void start() {
            }

            @Override
            public void end(boolean success) {
                if (UpdateAppManager.isUpdate()) {
                    if (!UpdateAppManager.isDownLoad()) {
                        Activity activity = AppManager.getAppManager().currentActivity();
                        if (activity instanceof LoginActivity && !activity.isFinishing()) {
                            UpdateAppManager.getUpdateAppManager().showDialog(LoginActivity.this,
                                    true);
                        }
                    } else {
                        ToastUtil.showShort(getResources().getString(R.string.isDownLoad));
                    }
                }
            }
        });
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 10001) {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable()) {
                taskFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            }
            File file = new File(taskFilePath + File.separator + UpdateAppManager.NAME);
            if (!file.exists()) return;
            new InstallUtil(LoginActivity.this, file.getAbsolutePath()).install();
        }
    }

    private void initEnterpriseWX() {
        iwwapi = WWAPIFactory.createWWAPI(this);
        iwwapi.registerApp(Constants.SCHEMA);
    }

    public void loginWX() {
        final WWAuthMessage.Req req = new WWAuthMessage.Req();
        req.sch = Constants.SCHEMA;
        req.appId = Constants.APPID;
        req.agentId = Constants.AGENTID;
        req.appPkg = getPackageName();
        req.appName = getString(getApplicationInfo().labelRes);
        req.state = "wwapitest";
        iwwapi.sendMessage(req, new IWWAPIEventHandler() {
            @Override
            public void handleResp(BaseMessage resp) {
                if (resp instanceof WWAuthMessage.Resp) {
                    WWAuthMessage.Resp rsp = (WWAuthMessage.Resp) resp;
                    if (rsp.errCode == WWAuthMessage.ERR_CANCEL) {
                        Toast.makeText(LoginActivity.this, "登录取消", Toast.LENGTH_SHORT).show();
                    } else if (rsp.errCode == WWAuthMessage.ERR_FAIL) {
                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    } else if (rsp.errCode == WWAuthMessage.ERR_OK) {
                        ModuleManager.getInstance().getWXLoginRequest(LoginActivity.this, rsp.code)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new BaseObserver<LoginResultBean>() {
                                    @Override
                                    protected void hideDialog() {
                                        stopProgressDialog();
                                    }

                                    @Override
                                    protected void showDialog() {
                                        startProgressDialog();
                                    }

                                    @Override
                                    protected void onSuccess(LoginResultBean data) {
                                        if (data == null) return;
                                        LoginResultBean.DataBean dataBean = data.getData();
                                        if (dataBean == null) return;
                                        LoginResultBean.DataBean.UserBean user = dataBean.getUser();
                                        if (user == null) {
                                            ToastUtil.showShort("用户信息获取失败，请重试");
                                            return;
                                        }
                                        SharePrefrenceHelper.setLoginMobile(user.getPhone());
                                        if (JPushInterface.isPushStopped(getApplicationContext())) {
                                            JPushInterface.resumePush(getApplicationContext());
                                            //设置极光推送alias
                                            setJpushAlias(user.getPhone());
                                        }
                                        SharePrefrenceHelper.setUser(user);
                                        LoginResultBean.DataBean.UserBean.DeptVoBean deptVo = user.getDeptVo();
                                        if (deptVo != null) {
                                            SharePrefrenceHelper.setIsVip(deptVo.isIsVip());
                                        }
                                        SharePrefrenceHelper.setLoginStatus(true);
                                        SharePrefrenceHelper.setLoginResultBean(data);
                                        SharePrefrenceHelper.setToken(dataBean.getToken());

                                        MainActivity.start(LoginActivity.this);
                                    }

                                    @Override
                                    protected void onFailure(String message) {
                                        ToastUtil.showShort(message);
                                    }
                                });
                    } else {
                        ToastUtil.showShort("错误码：" + rsp.errCode);
                    }
                } else {
                    ToastUtil.showShort("错误码：++++++++");
                }
            }
        });
    }

    @OnClick({R.id.iv_clear, R.id.btn_next_step, R.id.iv_wechat_login, R.id.tv_user_protocol, R.id.tv_privacy_policy})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_clear:
                mEtPhone.setText("");
                break;
            case R.id.iv_wechat_login:
                loginWX();
                break;
            case R.id.btn_next_step:
                if (TextUtils.isEmpty(mEtPhone.getText().toString().trim())) {
                    ToastUtil.showShort("手机号不允许为空");
                    return;
                }
                if (mEtPhone.getText().toString().trim().length() < 11) {
                    ToastUtil.showShort("手机号格式不正确");
                    return;
                }
                getVerify();
                break;
            case R.id.tv_user_protocol:
                NewsDetailActivity.start(this, URL_USER_PROTOCOL, "用户协议", true, false);
                break;
            case R.id.tv_privacy_policy:
                NewsDetailActivity.start(this, URL_PRIVACY_VOLICY, "隐私政策", true, false);
                break;
        }
    }

    private void setJpushAlias(String phoneNum) {
        TagAliasOperatorHelper.getInstance().handleAction(this, TagAliasOperatorHelper.ACTION_SET, TagAliasOperatorHelper.getInstance().getTagAliasBean(phoneNum));
    }

    private void getVerify() {
        ModuleManager.getInstance().getVerifyCodeRequest(this, mEtPhone.getText().toString().trim(), AppUtil.getIMEI(), System.currentTimeMillis())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new BaseObserver<BaseBean>() {
            @Override
            protected void hideDialog() {
                stopProgressDialog();
            }

            @Override
            protected void showDialog() {
                startProgressDialog();
            }

            @Override
            protected void onSuccess(BaseBean baseBean) {
                turnToVerifyCode();
            }

            @Override
            protected void onFailure(String message) {
                ToastUtil.showShort(message);
            }
        });
    }

    private void turnToVerifyCode() {
        Intent intent = new Intent(LoginActivity.this, VerifyCodeActivity.class);
        intent.putExtra("phoneNum", mEtPhone.getText().toString().trim());
        startActivity(intent);
    }

    @SuppressLint("CheckResult")
    private void requestPermission() {
        //同时请求多个权限
        RxPermissions rxPermission = new RxPermissions(LoginActivity.this);
        rxPermission.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.READ_PHONE_STATE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        LogUtil.d(permission.name + " is granted.");
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        LogUtil.d(permission.name + " is denied. More info should be provided.");
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        LogUtil.d(permission.name + " is denied.");
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iwwapi.unregisterApp();
    }
}
